import { onActivated, onDeactivated, reactive, toRefs, watch } from 'vue'

import IBaseObj from '#/index'

export const useAutoRefresh = () => {
  const state: IBaseObj = reactive({
    isRefreshing: true,
    refreshTimer: null,
    callbackFunc: () => {},
  })
  const { isRefreshing, refreshTimer } = toRefs(state)

  const setCallbackFunc = (func: Function) => {
    state.callbackFunc = func
  }

  const startRefresh = (func: Function = state.callbackFunc) => {
    state.refreshTimer && cancelRefresh()
    state.refreshTimer = window.setInterval(func, 30 * 1000)
  }

  const cancelRefresh = () => {
    window.clearInterval(state.refreshTimer)
    state.refreshTimer = null
  }

  watch(
    () => state.isRefreshing,
    (val) => {
      if (val) {
        startRefresh(state.callbackFunc)
      } else {
        if (state.refreshTimer) {
          cancelRefresh()
        }
      }
    },
    { immediate: true }
  )

  onActivated(() => {
    if (state.isRefreshing) {
      startRefresh()
    }
  })

  onDeactivated(() => {
    if (state.refreshTimer) {
      cancelRefresh()
    }
  })

  return {
    isRefreshing,
    refreshTimer,
    setCallbackFunc,
    startRefresh,
    cancelRefresh,
  }
}
